const { src, dest, series, parallel } = require("gulp");
const beautify = require("js-beautify").js;
const del = require("del");
const fs = require("fs");

/**
 * 根据目录生成 数组
 * folder/index.html
 * urlPrefix = http://hotblin.gitee.io/htmlexample/
 */
function buildUrlList() {
  const folders = fs.readdirSync("./static/");
  // const urlPrefix = "http://hotblin.gitee.io/htmlexample/";
  const list = folders.map(t => {
    return {
      name: t,
      url: `static/${t}/index.html`,
    };
  });
  const js = `var array = ${JSON.stringify(list)}`;

  const afterBeautifyJs = beautify(js, {
    indent_size: 2,
    space_in_empty_paren: true,
  });
  fs.writeFileSync("./index.js", afterBeautifyJs);
}

/**
 * 复制生成的 js 文件到 dist
 * @param {*} cb
 */
const buildUrlJs = cb => {
  buildUrlList();
  src("./index.js").pipe(dest("./dist/"));
  cb();
};

// 删除 dist 目录
const delDist = cb => {
  del.sync(["./dist"]);
  cb();
};

// 任务结束要删除生成的 js 文件
// const delBuildJs = cb => {
//   del.sync(["./index.js"]);
//   cb();
// };

// 复制静态文件
const copyAssets = cb => {
  src("style/**").pipe(dest("./dist/style/"));
  src("static/**").pipe(dest("./dist/static/"));
  src("index.html").pipe(dest("./dist/"));
  src("favicon.ico").pipe(dest("./dist/"));
  cb();
};

exports.default = series(delDist, parallel(buildUrlJs, copyAssets));
